package com.trackerapp.screen;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;
import com.trackerapp.CommonUtilities;
import com.trackerapp.R;
import com.trackerapp.util.NetworkConnectionUtil;
import com.trackerapp.util.TrackerPreferenceManager;

public class WelcomeActivity extends Activity {

	Button register;
	ProgressDialog mProgressDialog;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.welcome_layout);
		register = (Button) findViewById(R.id.register);
		
		checkNotNull(CommonUtilities.SENDER_ID, "SENDER_ID");
		mProgressDialog = ProgressDialog.show(this, "Registration" , "Please wait.Registering for Push Messaging... ", true);
		mProgressDialog.show();
        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);
       
        
        registerReceiver(mHandleMessageReceiver, new IntentFilter(CommonUtilities.REGISTERED_MESSAGE));
        registerReceiver(mHandleMessageReceiver, new IntentFilter(CommonUtilities.REGISTERED_SUCCESS_MESSAGE));
        registerReceiver(mHandleMessageReceiver, new IntentFilter(CommonUtilities.REGISTERED_ERROR_MESSAGE));
        registerReceiver(mHandleMessageReceiver, new IntentFilter(CommonUtilities.UNREGISTERED_SUCCESS_MESSAGE));
        registerGCM();
        
	}
    
	protected void onDestroy() {
		super.onDestroy();
		if( mHandleMessageReceiver != null) {
			unregisterReceiver(mHandleMessageReceiver);
			mHandleMessageReceiver = null;
		}
	}
	
	private void checkNotNull(Object reference, String name) {
        if (reference == null) {
            throw new NullPointerException(getString(R.string.error_config, name));
        }
    }

    private void registerGCM() {
        
		AsyncTask<Void, Void, Void> registerTask = new AsyncTask<Void, Void, Void>(){

			@Override
			protected Void doInBackground(Void...params) {
		        final String regId = GCMRegistrar.getRegistrationId(WelcomeActivity.this);
		        System.out.println(" Regsitration ID ************* "+regId);
		        
		        if (regId.equals("")) {
		        	if(!NetworkConnectionUtil.isOnline() ) {
		        		mProgressDialog.cancel();
		        		showToast("Need internet connection to register to start receving daily facts.");
		        	} else {
		        		System.out.println(" Rquest to register ************* ");
			            // Automatically registers application on startup.
			            GCMRegistrar.register(WelcomeActivity.this, CommonUtilities.SENDER_ID);
		        	}
		        } else {
		            // Device is already registered on GCM, check server.
		            if (GCMRegistrar.isRegisteredOnServer(WelcomeActivity.this)) {
		                // Skips registration.
		            	System.out.println(" ALready registered 111 ************* ");
		            	mProgressDialog.cancel();
		                //mDisplay.append(getString(R.string.already_registered) + "\n");
		            } else {
		                // Try to register again, but not in the UI thread.
		                // It's also necessary to cancel the thread onDestroy(),
		                // hence the use of AsyncTask instead of a raw thread.
//                        boolean registered = ServerUtilities.register(DashboardScreen.this, regId);
//                        if (!registered) {
//                            GCMRegistrar.unregister(DashboardScreen.this);
//                        }
		            	mProgressDialog.cancel();
		            	System.out.println(" ALready registered 222 ************* ");
		        		startRegistration(regId);
		            }
		        }
				return null;
			}
		};
		
		registerTask.execute();

    }
    
    private void startRegistration(String regId) {
    	if(!TrackerPreferenceManager.getString(TrackerPreferenceManager.PreferenceKeys.DEVICE_ID, "").equals("")) {
    		Intent registerIntent = new Intent(WelcomeActivity.this,TrackDeliveryActivity.class);
    		WelcomeActivity.this.startActivity(registerIntent);
    		System.out.println(" #### start landing screen ##### ");
        	finish();
        	return;
    	}
		Intent registerIntent = new Intent(WelcomeActivity.this,RegisterAccessCodeActivity.class);
		registerIntent.putExtra("gcmid", regId);
		WelcomeActivity.this.startActivity(registerIntent);
		System.out.println(" #### start registration ##### "+regId);
    	finish();
    }
	
    private BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
	        @Override
	        public void onReceive(Context context, Intent intent) {
	        	
	        	System.out.println(" ON RECEIVE *************** "+intent.getAction());
	        	
	        	if (intent.getAction().equals(CommonUtilities.REGISTERED_MESSAGE)) {
	        		String newMessage = intent.getExtras().getString(CommonUtilities.EXTRA_MESSAGE);
	        		showToast(newMessage);
	        		startRegistration(newMessage);
	        		System.out.println(" ON RECEIVE REGISTERED MESSAGE *************** ");
	        		mProgressDialog.cancel();
	        	} else if (intent.getAction().equals(CommonUtilities.REGISTERED_SUCCESS_MESSAGE)) {
	        		
	        		String newMessage = intent.getExtras().getString(CommonUtilities.EXTRA_MESSAGE);
	        		System.out.println(" ON RECEIVE REGISTERED SUCCESS MESSAGE *************** "+newMessage);
	        		startRegistration(newMessage);
	        		mProgressDialog.cancel();
	        		showToast(intent.getExtras().getString(CommonUtilities.EXTRA_MESSAGE));
	        	} else if (intent.getAction().equals(CommonUtilities.REGISTERED_ERROR_MESSAGE)) {
	        		mProgressDialog.cancel();
	        		showToast(intent.getExtras().getString(CommonUtilities.EXTRA_MESSAGE));
	        	} else if (intent.getAction().equals(CommonUtilities.UNREGISTERED_SUCCESS_MESSAGE)) {
	        		mProgressDialog.cancel();
	        		showToast(intent.getExtras().getString(CommonUtilities.EXTRA_MESSAGE));
	        	} 

	        }
	    };
	    
	    private void showToast(final String message) {
	    	runOnUiThread( new Runnable() {
	    		public void run() {
	    			Toast.makeText(WelcomeActivity.this, message, Toast.LENGTH_LONG).show();
	    		}
	    	});
	    }
}

